# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import random
import logging

from models import OAuthUploadSignatures

try:
    import uuid

    _generate_uuid = lambda: uuid.uuid4().hex
except ImportError:
    logging.info("No uuid module, using fake")
    _generate_uuid = lambda: str(random.randint(10000000, 20000000))

def new_uuid():
    return _generate_uuid()

OAUTH_PREFIX = "oauth"

def remove_oauth_params(params):
    p = {}
    for (k, v) in params.iteritems():
        if isinstance(k, (unicode)):
            k = str(k)
        if not k.startswith(OAUTH_PREFIX):
            p[k] = v
    return p


class OAuthError(RuntimeError):
    def __init__(self, message="OAuth error occured."):
        RuntimeError.__init__(self, message)
        self.message = message

    def __str__(self):
        return "<OAuthError: %s>" % (self.message)


def create_upload_signature(uid):
    sign = new_uuid()
    db_signature = OAuthUploadSignatures.insert_sign(uid, sign)
    return db_signature.signature


def check_upload_signature_and_delete(sign):
    db_signature = OAuthUploadSignatures.check_sign_exist(sign)
    if db_signature:
        user_uid = db_signature.uid
        db_signature.delete()
        return user_uid

    return False


def main():
    pass

if __name__ == '__main__':
    main()
